package org.example.springboot.controller;

import org.example.springboot.common.Result;
import org.example.springboot.entity.User;
import org.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 功能：
 * 作者：扫钢
 * 日期：2024/11/14 19:58
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        try {
            userService.insertUser(user);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据库错误");
            } else {
                return Result.error();
            }
        }
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateUser(user);
        return Result.success(user);
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        userService.deleteUser(id);
        return Result.success(id);
    }

    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        userService.batchDeleteUser(ids);
        return Result.success(ids);
    }

    @GetMapping("/selectAll")
    public Result selectAll() {
        List<User> list = userService.selectAllUser();
        return Result.success(list);
    }

    @GetMapping("/selectByid/{id}")
    public Result selectById(@PathVariable Integer id) {
        User user = userService.selectUserById(id);
        return Result.success(user);
    }

    @GetMapping("/selectByMore")
    public Result selectByMore(String name, String phone) {
        List<User> ls = userService.selectUserByMore(name, phone);
        return Result.success(ls);
    }

    @GetMapping("/selectByMo")
    public Result selectByMo(@RequestParam String name, @RequestParam String phone) {
        List<User> ls = userService.selectUserByMo(name, phone);
        return Result.success(ls);
    }

    @GetMapping("/selectByPage")
    public Result selectByPage(String name,
                               String phone,
                               Integer pageNum,
                               Integer pageSize) {
        Map<String, Object> result = userService.selectUserByPage(name, phone, pageNum, pageSize);
        return Result.success(result);
    }

}